package com.example.leetdemo.plan1;

public class Sword002 {

    public String addBinary(String a, String b) {
        int up = 0;
        StringBuilder builder = new StringBuilder();
        int min = Math.min(a.length(), b.length());
        for (int i = 1; i <= min; i++) {
            int an = a.charAt(a.length() - i) - '0';
            int bn = b.charAt(b.length() - i) - '0';
            if (up + an + bn == 3) {
                builder.append('1');
                up = 1;
            } else if (up + an + bn == 2) {
                builder.append('0');
                up = 1;
            } else {
                builder.append(an + bn + up);
                up = 0;
            }
        }
        String maxStr = a.length() > b.length() ? a : b;
        for (int i = maxStr.length() - min - 1; i >= 0; i--) {
            int n = maxStr.charAt(i) - '0';
            if (up + n == 3) {
                builder.append('1');
                up = 1;
            } else if (up + n == 2) {
                builder.append('0');
                up = 1;
            } else {
                builder.append(n + up);
                up = 0;
            }
        }
        if (up == 1) {
            builder.append(1);
        }
        return builder.reverse().toString();
    }

    public static void main(String[] args) {
        Sword002 sword002 = new Sword002();
        System.err.println(sword002.addBinary("100", "110010"));
    }
    public static class BinarySum {
        public static String binarySum(String a, String b) {
            int i = a.length() - 1, j = b.length() - 1;
            int carry = 0; StringBuilder result = new StringBuilder();
            while (i >= 0 || j >= 0) {
                int sum = carry; if (i >= 0) sum += a.charAt(i--) - '0';
                if (j >= 0) sum += b.charAt(j--) - '0';
                result.append(sum % 2); carry = sum / 2;
            }
            if (carry != 0) result.append(carry);
            return result.reverse().toString();
        }

        public static void main(String[] args) {
            String a = "101";
            String b = "110";
            System.out.println(binarySum(a, b));
        }
    }
}
